package com.wjy.game.utils;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

/**
 * @author wjy
 * @date 2025/5/16 16:10
 * @description Protostuff工具
 */
public class ProtostuffUtil {

    /**
     * 序列化
     * 
     * @param obj
     * @return
     */
    public static byte[] serialize(Object obj) {
        if (obj != null) {
            Schema schema = RuntimeSchema.getSchema(obj.getClass());
            return ProtobufIOUtil.toByteArray(obj, schema, LinkedBuffer.allocate());
        }
        return null;
    }

    /**
     * 反序列化
     * 
     * @param bytes
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes != null && clazz != null) {
            Schema<T> schema = RuntimeSchema.getSchema(clazz);
            T obj = schema.newMessage();
            ProtobufIOUtil.mergeFrom(bytes, obj, schema);
            return obj;
        }
        return null;
    }

}
